package main.leetcode.offer.secondround.from03to50;

import main.datastruc.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/** 32-II.从上到下打印二叉树 */
public class ex32II {
    private List<List<Integer>> res = new ArrayList<>();

    public static void main(String[] args) {
        TreeNode root = TreeNode.creCmpBTree(new int[] {3, 9, 20, 1, 1, 15, 7});
        System.out.println(new ex32II().levelOrder(root));
    }

    /** 迭代 */
    public List<List<Integer>> levelOrder1(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        TreeNode node;
        List<Integer> tmp;
        while (!queue.isEmpty()) {
            tmp = new ArrayList<>();
            int n = queue.size();
            // 按层添加
            for (int i = 0; i < n; ++i) {
                node = queue.poll();
                tmp.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            res.add(tmp);
        }
        return res;
    }

    /** 递归 */
    public List<List<Integer>> levelOrder(TreeNode root) {
        dfs(root, 0);
        return res;
    }

    private void dfs(TreeNode root, int level) {
        if (root == null) {
            return;
        }
        // 第一时间到达该层，创建一个新的list
        if (level + 1 > res.size()) {
            res.add(new ArrayList<>());
        }
        res.get(level).add(root.val);
        dfs(root.left, level + 1);
        dfs(root.right, level + 1);
    }
}
